package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.PasswordLoginBody;
import com.ruoyi.common.core.domain.model.UserModel;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.edh.domain.EdhMicroshop;
import com.ruoyi.edh.mapper.EdhMicroshopMapper;
import com.ruoyi.edh.service.IIMService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IIMService iimService;

    @Autowired
    private EdhMicroshopMapper microshopMapper;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @param userType 用户类型 （使用userConstans常量）
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName, String userType) {
        return userMapper.selectUserByUserName(userName, userType);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber(), user.getUserType());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param phonenumber 手机号
     * @param userType    用户类型 00系统用户 11 app用户
     * @return
     */
    @Override
    public String checkPhoneUnique(String phonenumber, String userType) {

        SysUser info = userMapper.checkPhoneUnique(phonenumber, userType);
        if (StringUtils.isNotNull(info)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail(), user.getUserType());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 后台新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * app新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(UserModel.Logon user) {
        String cacheCode = redisCache.getCacheObject(UserConstants.APP_USER_LOGON_MESSAGE_PRIFEX + user.getPhonenumber());
        if (StringUtils.isEmpty(cacheCode)) {
            throw new CustomException("验证码不存在");
        } else if (StringUtils.isEmpty(user.getCode())) {
            throw new CustomException("请输入验证码");
        } else if (!user.getCode().equals(cacheCode)) {
            throw new CustomException("验证码错误,请检查后重新输入");
        }

        Long invitees;
        SysUser insertUser = new SysUser();
        insertUser.setUserType(UserConstants.APP_USER);
        insertUser.setInvitees(user.getInvitees());
        insertUser.setPassword(user.getPassword());
        insertUser.setPhonenumber(user.getPhonenumber());
        insertUser.setAvatar("/profile/avatar/2020/11/16/59b069ea-5d65-4575-9701-9868866d1b99.jpeg");
        insertUser.setUserName(user.getPhonenumber());
        insertUser.setNickName(user.getPhonenumber());
        // 新增用户信息
        int rows = userMapper.insertUser(insertUser);

        // 开通极光账号
        iimService.register(insertUser);
        // 开通微店
        EdhMicroshop microshop = new EdhMicroshop();
        microshop.setName(insertUser.getNickName() + "的微店");
        microshop.setUserId(insertUser.getUserId());
        microshop.setImage(insertUser.getAvatar());
        microshop.setCreateBy(insertUser.getUserId().toString());
        microshopMapper.insertEdhMicroshop(microshop);

        // 如果邀请人不为空的话
        if (StringUtils.isNotNull(invitees = user.getInvitees())) {
            SysUser searchUser = new SysUser();
            searchUser.setInvitees(invitees);
            // 团长邀请人达到50人则升级为团长
            List<SysUser> sysUsers = userMapper.selectUserList(searchUser);
            if (null != sysUsers && UserConstants.TEAM_THRESHOLD <= sysUsers.size()) {
                SysUser userleader = userMapper.selectUserById(invitees);
                if (StringUtils.isNull(userleader)) {
                    log.error("邀请人id异常,请手动绑定邀请人");
                    return rows;
                }
                userleader.setTeamLeader("1");
                userleader.setTeamLeaderTime(DateUtils.getNowDate());
                userMapper.updateUser(userleader);
            }
        }

        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        if (!UserConstants.APP_USER.equals(user.getUserType())) {
            // 删除用户与角色关联
            userRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            insertUserRole(user);
            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(user.getNickName())) {
            loginUser.getUser().setNickName(user.getNickName());
        }
        if (StringUtils.isNotNull(user.getSex())) {
            loginUser.getUser().setSex(user.getSex());
        }
        iimService.update(loginUser.getUser());
        redisCache.setCacheObject(Constants.LOGIN_TOKEN_KEY + loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName(), UserConstants.APP_USER);
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 微信openid绑定手机号
     *
     * @param openId 微信openId
     * @param phone  手机号
     * @param code   手机验证码
     * @return
     */
    @Override
    public Integer wxBindPhone(String openId, String phone, String code) {

        String cacheCode = redisCache.getCacheObject(UserConstants.APP_USER_WXBINDPHONE_MESSAGE_PRIFEX + phone);
        if (StringUtils.isEmpty(cacheCode)) {
            throw new CustomException("验证码不存在");
        } else if (StringUtils.isEmpty(code)) {
            throw new CustomException("请输入验证码");
        } else if (!code.equals(cacheCode)) {
            throw new CustomException("验证码错误,请检查后重新输入");
        }
        SysUser user = userMapper.selectUserByUserName(phone, UserConstants.APP_USER);
        if (StringUtils.isNull(user)) {
            throw new CustomException("您的手机号" + phone.substring(0, 3) + "****" + phone.substring(7) + "尚未注册", HttpStatus.NOT_LOGON);
        }
        user.setOpenId(openId);
        userMapper.updateUser(user);
        return 1;
    }

    /**
     * 更换绑定手机号
     *
     * @param newPhone 新手机号
     * @param oldPhone 旧手机号
     * @return
     */
    @Override
    public Integer changePhone(String newPhone, String oldPhone, String code) {
        String cacheCode = redisCache.getCacheObject(UserConstants.APP_USER_CHANGE_PASSWORD + newPhone);
        if (!code.equals(cacheCode)) {
            throw new CustomException("验证码不正确");
        }
        SysUser user = userMapper.selectUserByUserName(oldPhone, UserConstants.APP_USER);
        user.setPhonenumber(newPhone);
        userMapper.updateUser(user);
        return 1;
    }

    /**
     * 填写我的邀请人
     *
     * @param invitees 邀请人id
     * @return int
     */
    @Override
    public Integer additionalInvitees(Long invitees) {
        SysUser me = userMapper.selectUserById(SecurityUtils.getUserId());
        if (invitees.equals(me.getUserId())) {
            throw new CustomException("不能自己邀请自己哦");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.setUser(me);
        redisCache.setCacheObject(Constants.LOGIN_TOKEN_KEY + loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES);
        if (StringUtils.isNotNull(me.getInvitees())) {
            throw new CustomException("您已有团长！");
        }

        SysUser user = userMapper.selectUserById(invitees);
        if (StringUtils.isNull(user)) {
            throw new CustomException("团长ID不存在，请重试");
        }
        me.setInvitees(invitees);
        userMapper.updateUser(me);

        SysUser searchUser = new SysUser();
        searchUser.setInvitees(invitees);
        // 团长邀请人达到50人则升级为团长
        List<SysUser> sysUsers = userMapper.selectUserList(searchUser);
        if (null != sysUsers && UserConstants.TEAM_THRESHOLD <= sysUsers.size()) {
            user.setTeamLeader("1");
            user.setTeamLeaderTime(DateUtils.getNowDate());
            userMapper.updateUser(user);
        }
        return 1;
    }

    /**
     * 忘记密码验证手机号
     *
     * @param phonenumber 用户手机号验证码信息
     * @param code        验证码信息
     */
    @Override
    public String verifyPhone(String phonenumber, String code) {
        SysUser user1 = userMapper.selectUserByUserName(phonenumber, UserConstants.APP_USER);
        if (StringUtils.isNull(user1)) {
            throw new CustomException("该手机号未注册,请检查后重试");
        }
        String cacheCode = redisCache.getCacheObject(UserConstants.APP_USER_FORGETPASSWORD_MESSAGE_PRIFEX + phonenumber);
        if (StringUtils.isEmpty(cacheCode)) {
            throw new CustomException("验证码不存在");
        } else if (StringUtils.isEmpty(code)) {
            throw new CustomException("请输入验证码");
        } else if (!code.equals(cacheCode)) {
            throw new CustomException("验证码错误,请检查后重新输入");
        }
        return phonenumber;
    }

    /**
     * app用户修改密码
     *
     * @param user 用户修改密码信息
     */
    @Override
    public Integer appUpdatePassword(UserModel.UpdatePassword user) {
        return userMapper.resetUserPwd(user.getPhonenumber(), user.getPassword());
    }

    /**
     * 通过邮箱找回密码
     *
     * @param user
     */
    @Override
    public Integer forgotPasswordbymail(PasswordLoginBody.UpdatePassword user) {
        // 此处用户不为app用户的话 其他皆为一样的结果
        SysUser user1 = userMapper.checkEmailUnique(user.getEmail(), UserConstants.SYSTEM_USER);
        if (StringUtils.isNull(user1)) {
            throw new CustomException("邮箱不存在,请检查后重试");
        }
        Object cacheObject = redisCache.getCacheObject(user.getEmail());
        if (StringUtils.isNull(cacheObject)) {
            throw new CustomException("邮箱验证码不存在,请重新发送验证码");
        }
        if (!user.getCode().equals((String) cacheObject)) {
            throw new CustomException("邮箱验证码不一致,请检查后重新填写");
        }
        user1.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        return userMapper.updateUser(user1);
    }

    /**
     * 升级为队长
     *
     * @param userId
     */
    @Override
    public Integer updateToTeamLeader(Long userId, String teamLeader) {
        return userMapper.updateToTeamLeader(userId, teamLeader);
    }

    /**
     * 获取优惠券个数和可提现金额
     */
    @Override
    public List<Map<String, Object>> personalAsset() {
        Long userId = SecurityUtils.getUserId();
        return userMapper.personalAsset(userId);
    }

    @Override
    public void checkCode(String phone, String code) {
        String cacheCode = redisCache.getCacheObject(UserConstants.APP_USER_CHANGE_PASSWORD + phone);
        if (!code.equals(cacheCode)) {
            throw new CustomException("验证码错误");
        }
    }

    @Override
    public Map<String, Object> myInvitees() {
        Map<String, Object> result = new HashMap<String, Object>(16);
        Long userId = SecurityUtils.getUserId();
        SysUser user = new SysUser();
        user.setInvitees(userId);
        // 我邀请的人数
        result.put("myInviteesNumber", userMapper.selectMyInvitees(userId));
        result.put("myInvitees", userMapper.selectUserList(user));
        return result;
    }
}
